#include "headset_at_commands.h"
#include <string.h>
#include <byte_utils.h>
#include <stdlib.h>
#include <bt_device.h>
#include "battery_monitor.h"
#include "hfp_profile.h"
#include "logging.h"
 
typedef struct
{
    TaskData task;
    batteryRegistrationForm Client; 
} atCmdTaskData;
 
atCmdTaskData atCmdTask; 
 
/* vender id - product id - version- report bit */
// static const char batt_enable_string[]   = "AT+XAPL=05AC-1702-0100,9\r";
static const char batt_level_string[]   = "AT+IPHONEACCEV=1,1,0\r";
#define BATT_POS   19
 
void HfpEnableBattReport(void)
{
    // HfpAtCmdRequest(hfp_primary_link, batt_enable_string);
}
 
void HfpAtCmdSendBatt(uint16 voltage_mv)
{
    char *at_command_data;
    uint8 percent;
    if (voltage_mv>=4200)
    {
        percent = 100;
    }else if (voltage_mv<=3000)
    {
        percent = 0;
    }else
    {
        percent = 100UL * (uint32)(voltage_mv - 3000) / (uint32)(4200 - 3000);
    }
    DEBUG_LOG_VERBOSE("HfpAtCmdSendBatt: %d",percent);
    at_command_data = malloc(sizeof(batt_level_string));
    if (at_command_data)
    {
        memcpy(at_command_data, batt_level_string, sizeof(batt_level_string));
        if(100 != percent)
            at_command_data[BATT_POS] = (percent/10) + '0';
        else
            at_command_data[BATT_POS] = '9';
        // HfpAtCmdRequest(hfp_primary_link, at_command_data);
    }
    free(at_command_data);
}
 
static void hfpAtCmdHandleMessage(Task task, MessageId id, Message message)
{
    UNUSED(task);
 
    switch (id)
    {
        case MESSAGE_BATTERY_LEVEL_UPDATE_VOLTAGE:
            if(appHfpIsConnected())
                HfpAtCmdSendBatt(((MESSAGE_BATTERY_LEVEL_UPDATE_VOLTAGE_T *)message)->voltage_mv);
            break;
            
        default:
            break;
    }
}
 
bool hfpAtCmdInit(Task init_task)
{
    UNUSED(init_task);
 
    atCmdTask.task.handler = hfpAtCmdHandleMessage;
 
    atCmdTask.Client.task = &atCmdTask.task;
    atCmdTask.Client.hysteresis = 1;
    atCmdTask.Client.representation = battery_level_repres_voltage;
 
    appBatteryRegister(&atCmdTask.Client);
 
    return TRUE;
}
